package com.aop.example.controller;

import com.aop.example.annotation.Authority;
import com.aop.example.annotation.LogAnnotation;
import com.aop.example.aspect.AuthorityUtil;
import com.aop.example.aspect.RedisEnum;
import com.aop.example.mapper.PermissionMapper;
import com.aop.example.mapper.UserMapper;
import com.aop.example.pojo.User;
import com.aop.example.pojo.data.PermissionList;
import com.aop.example.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.domain.dto.permission.PermissionDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Tag(name = "测试登录管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    AuthorityUtil authorityUtil;

    @Operation(summary = "登录测试接口")
    @GetMapping("/login/{username}/{password}")
    public String login(@PathVariable String username, @PathVariable String password){
        User loginUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", username).eq("password",password));
        if( loginUser == null){
            return null;
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", loginUser.getUserId());
        claims.put("username", loginUser.getUsername());
        String token = JwtUtil.genToken(claims);
        System.out.println(token);
        String key = RedisEnum.Login_TOKEN_KEY.getPrefix() + token;
        redisTemplate.opsForValue().set(key, token, 30, TimeUnit.MINUTES);
        return token;
    }

    @Operation(summary = "获取权限列表接口")
    @GetMapping("/permission/{userId}")
    public PermissionList getPermissionList(@PathVariable Integer userId){
        List<String> permissionList = permissionMapper.getPermissionListByUserId(userId);
        System.out.println(permissionList);
        boolean addRow = authorityUtil.addAuth(userId, permissionList);
        if(!addRow){
            throw new RuntimeException("保存数据失败");
        }
        return new PermissionList(userId, permissionList);
    }

    @Operation(summary = "删除用户的接口")
    @Authority("system:user:remove")
    @DeleteMapping("/del/{userId}")
    public Integer delPermission(@PathVariable Integer userId){
        int delRow = userMapper.deleteById(userId);
        System.out.println(delRow);
        return delRow;
    }

    @Operation(summary = "首页展示")
    @Authority("system:info")
    @GetMapping("/info")
    public Integer LoginInfo(){
       return 1;
    }
}
